/**
 * Mock security
 * @author Wangtd
 */
const md5 = require('md5-node');

const config = require('../config.js');
const util = require('./util.js');
const logger = require('./logger.js');

function fetchRememberMeUser(request) {
    if (request.cookies.remember_me) {
        var token = new Buffer(request.cookies.remember_me, 'base64');
        var users = JSON.parse(util.readFileSync(config.workDir + '/users.json'));
        for (var i = 0; i < users.length; i++) {
            if (md5(users[i].username + ':' + users[i].password) == token) {
                request.session.user = users[i];
                break;
            }
        }
    }
}

module.exports.fetchRememberMe = fetchRememberMeUser;

module.exports.checkPermission = function(request, response, next) {
    if (request.method == 'GET') {
        return next();
    }
    var url = request.originalUrl;
    // check remember me
    if (!request.session.user) {
        logger.info(request, 'Fetch remember me user, url=%s', url);
        fetchRememberMeUser(request);
    }
    // check session user
    if (request.session.user) {
        if (/\/delete/.test(url) && request.session.user.role != 'admin') {
            logger.info(request, 'Forbidden(403), url=%s', url);
            response.status(403).end();
        } else {
            next();
        }
    } else {
        logger.info(request, 'Unauthorized(401), url=%s', url);
        response.status(401).end();
    }
}
